<?php
declare(strict_types=1);

namespace App\Model;

use Carbon\Carbon;
use Hyperf\Utils\Str;

/**
 * @property int $id
 * @property string $path
 * @property string $real_path
 * @property string $url
 * @property string $extension
 * @property string $title
 * @property Carbon $created_at
 * @property Carbon $updated_at
 */
class ContentStatic extends MyBaseModel
{
    const URL_PREFIX = '/static';

    const PATH_ROOT = BASE_PATH . '/public' . self::URL_PREFIX;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'content_static';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    protected $appends = [
        'url',
        'real_path',
    ];

    public static function genPath(): string
    {
        $md5 = md5(strval(microtime(true)));
        return substr($md5, 0, 2) . '/' . substr($md5, 2) . Str::random(7);
    }

    public function getUrlAttribute(): string
    {
        if (!$this->path) {
            return '';
        }
        return static::getUrl($this->path, $this->extension);
    }

    public static function getUrl(string $path, string $extension): string
    {
        return env('STATIC_HOST', '') . static::URL_PREFIX . '/' . $path . $extension;
    }

    public function getRealPathAttribute(): string
    {
        if (!$this->path) {
            return '';
        }
        return static::getRealPath($this->path, $this->extension);
    }

    public static function getRealPath(string $path, string $extension): string
    {
        return static::PATH_ROOT . '/' . $path . $extension;
    }
}
